package com.rongshu.view.discovery.activity;

import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.rongshu.R;
import com.rongshu.utils.Common;
import com.rongshu.utils.Constant;
import com.rongshu.utils.LoginUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.base.mvp.INetBean;
import com.rongshu.view.discovery.adapter.TaAttentionAdapter;
import com.rongshu.view.discovery.bean.AuthorDetailBean;
import com.rongshu.view.discovery.bean.SearchAuthorResponse;
import com.rongshu.view.discovery.presenter.TaAttentionPresenter;
import com.rongshu.view.home.listener.OnItemMoreClickListener;
import com.rongshu.view.userInfo.activity.PersonDetailsActivity;
import com.rongshu.view.userInfo.iview.AttentionView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.rongshu.utils.UserInfoUtils.getUserId;

public class TaAttentionAcitivity extends BaseActivity<TaAttentionPresenter> implements AttentionView, OnItemMoreClickListener {
    @BindView(R.id.txt_top_title)
    TextView txt_top_title;//标题
    @BindView(R.id.recyclerView)
    RecyclerView attention_recyclerview;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.layout_empty)
    RelativeLayout layout_empty;
    @BindView(R.id.empty_hint)
    TextView emptyHint;
    @BindView(R.id.empty_img)
    ImageView emptyImg;
    private List<AuthorDetailBean> mAuthorDetailBeans;
    //manager
    private LinearLayoutManager manager = null;
    //adapter
    private TaAttentionAdapter adapter = null;
    //map
    private Map<String, Object> map = null;
    private int pageIndex = 1;
    private int pageSize = 15;
    //refresh,load
    private Intent intent;
    private int userId;
    private int ConcernWithPostion;
    private int type;
    public static int ATTENTION = 1;
    public static int FANS = 2;
    //request
    private final int REQUEST = 0x01;

    @Override
    protected int initLayout() {
        return R.layout.activity_attention_view;
    }

    @Override
    protected void initView() {
        intent = getIntent();
        if (intent != null) {
            userId = intent.getIntExtra(Constant.USER_ID, 0);
            type = intent.getIntExtra(Constant.INTENT_TYPE, 0);
        }
        //设置title
        if (type == ATTENTION) {
            txt_top_title.setText("Ta的关注");
            emptyHint.setText("Ta还未添加关注哦～");
            emptyImg.setImageResource(R.drawable.empty_attention_bg);
        } else {
            txt_top_title.setText("Ta的粉丝");
            emptyHint.setText("Ta还没有粉丝哦～");
            emptyImg.setImageResource(R.drawable.empty_fans_bg);
        }
        //set preseter
        setPresenter(new TaAttentionPresenter(this), this);
        //layoutmanager
        manager = new LinearLayoutManager(this);
        mAuthorDetailBeans = new ArrayList<>();
        //adapter
        adapter = new TaAttentionAdapter(this, mAuthorDetailBeans);
        adapter.setHasStableIds(true);
        adapter.setOnItemChildClickListener(this);
        //recyclerview
        attention_recyclerview.setLayoutManager(manager);
        attention_recyclerview.setAdapter(adapter);
        //触发自动刷新
        refreshLayout.autoRefresh();
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshlayout) {
                pageIndex = 1;
                refreshlayout.resetNoMoreData();
                getTaUserRelationships();
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                pageIndex++;
                getTaUserRelationships();
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    /**
     * 获取Ta的主页 关注 1，粉丝 2
     */
    private void getTaUserRelationships() {
        //user_id
        int user_id = getUserId();
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("ta_user_id", userId);
        map.put("type", type);
        map.put("page", pageIndex);
        map.put("pageSize", pageSize);
        presenter.getTaUserRelationships(user_id, userId, type,
                pageIndex, pageSize, Common.encryptionSign(map));
        map.clear();
    }

    @OnClick({R.id.layout_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_back:
                finish();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST:
                    if (data != null) {
                        boolean isConcern = data.getBooleanExtra(Constant.IS_COLLECT, false);
                        //状态
                        if (!isConcern) {
                            mAuthorDetailBeans.get(ConcernWithPostion).setIs_guanzhu(0);
                            mAuthorDetailBeans.get(ConcernWithPostion).setIs_mutual(0);
                        } else {
                            mAuthorDetailBeans.get(ConcernWithPostion).setIs_guanzhu(1);
                            int Tais_guanzhu = mAuthorDetailBeans.get(ConcernWithPostion).getTais_guanzhu();
                            if (Tais_guanzhu == 1) {
                                mAuthorDetailBeans.get(ConcernWithPostion).setIs_mutual(1);
                            }else {
                                mAuthorDetailBeans.get(ConcernWithPostion).setIs_mutual(0);
                            }
                        }
                        adapter.notifyDataSetChanged();
                    }
                    break;
            }
        }
    }

    /**
     * 我的关注信息回调
     */
    @Override
    public void onAttentionUser(SearchAuthorResponse response) {
        if (response != null && response.getResponse() != null) {
            List<AuthorDetailBean> authorDetailBeans = response.getResponse();
            if (pageIndex == 1) {
                mAuthorDetailBeans.clear();
            }
            if (refreshLayout.isLoading()) {
                refreshLayout.finishLoadmore();
            }
            if (refreshLayout.isRefreshing()) {
                refreshLayout.finishRefresh();
            }
            mAuthorDetailBeans.addAll(authorDetailBeans);
            adapter.notifyDataSetChanged();
            if (mAuthorDetailBeans == null || mAuthorDetailBeans.size() == 0) {
                layout_empty.setVisibility(View.VISIBLE);
                refreshLayout.setVisibility(View.GONE);
            }
            if (authorDetailBeans.size() == 0) {
                refreshLayout.finishLoadmoreWithNoMoreData();
            }
        }
    }

    /**
     * 取消/关注回调
     *
     * @param bean
     */
    @Override
    public void onCancleConcern(INetBean bean) {
        AuthorDetailBean authorDetailBean = mAuthorDetailBeans.get(ConcernWithPostion);
        //状态
        if (authorDetailBean.getIs_guanzhu() != 0) {
            toast(getString(R.string.cancel_attention_success));
            mAuthorDetailBeans.get(ConcernWithPostion).setIs_guanzhu(0);
            mAuthorDetailBeans.get(ConcernWithPostion).setIs_mutual(0);
        } else {
            toast(getString(R.string.add_attention_success));
            mAuthorDetailBeans.get(ConcernWithPostion).setIs_guanzhu(1);
            int Tais_guanzhu = mAuthorDetailBeans.get(ConcernWithPostion).getTais_guanzhu();
            if (Tais_guanzhu == 1) {
                mAuthorDetailBeans.get(ConcernWithPostion).setIs_mutual(1);
            }else {
                mAuthorDetailBeans.get(ConcernWithPostion).setIs_mutual(0);
            }
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onItemClick(View view, int position) {
        ConcernWithPostion = position;
        AuthorDetailBean detailBean = mAuthorDetailBeans.get(ConcernWithPostion);
        if (detailBean.getIs_guanzhu() == 1) {
            presenter.cancelConcernWith(detailBean.getUser_id_to());
        } else {
            presenter.ConcernWith(detailBean.getUser_id_to());
        }
    }

    @Override
    public void onUserHeaderClick(int postion, int userIdTo,boolean is_allow_browse_homepage) {
        ConcernWithPostion = postion;
        int user_id = getUserId();
        if (user_id == 0) {
            LoginUtils.toLogin(this);
            return;
        }
        Intent intent = null;
        if (user_id == userIdTo) {
            intent = new Intent(this, PersonDetailsActivity.class);
        } else {
            if (!is_allow_browse_homepage) {
                toast("由于对方的设置，你暂时无法浏览他的主页");
                return;
            }
            intent = new Intent(this, UserHomePageActivity.class);
            intent.putExtra(Constant.USER_ID, userIdTo);
        }
        startActivityForResult(intent, REQUEST);
    }
}
